<template>
    <div class="health-indicator-container">
        <div class="header">
            <!-- 新增用户ID输入框 -->
            <div class="user-id-input" v-if="isAdminOrDoctor">
                <el-input v-model="searchForm.userId" placeholder="请输入用户ID" clearable style="width: 200px"
                    @change="handleSearch">
                    <template #prepend>用户ID</template>
                </el-input>
            </div>
            <div class="search">
                <el-date-picker v-model="searchForm.startDate" type="date" placeholder="开始日期" format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD" @change="handleSearch" />
                <el-date-picker v-model="searchForm.endDate" type="date" placeholder="结束日期" format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD" @change="handleSearch" />
            </div>
            <el-button type="success" @click="handleAdd">新增指标</el-button>
        </div>

        <el-table :data="tableData" border style="width: 100%" height="450">
            <el-table-column prop="indicatorId" label="指标ID" width="80" />
            <el-table-column prop="height" label="身高(cm)" width="120" />
            <el-table-column prop="weight" label="体重(kg)" width="120" />
            <el-table-column prop="bmi" label="BMI" width="100" />
            <el-table-column prop="bloodPressure" label="血压" width="120" />
            <el-table-column prop="bloodGlucose" label="血糖" width="120" />
            <el-table-column prop="bloodOxygen" label="血氧" width="100" />
            <el-table-column prop="heartRate" label="心率" width="100" />
            <el-table-column label="创建时间" width="180">
                <template #default="scope">
                    {{ formatDate(scope.row.createdAt) }}
                </template>
            </el-table-column>
            <el-table-column label="操作" width="200">
                <template #default="scope">
                    <el-button type="primary" size="small" @click="handleUpdate(scope.row)">编辑</el-button>
                    <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 编辑对话框 -->
        <el-dialog v-model="dialogVisible" :title="dialogTitle" width="30%">
            <el-form :model="form" label-width="100px">
                <el-form-item label="身高(cm)">
                    <el-input-number v-model="form.height" :min="0" :precision="1" />
                </el-form-item>
                <el-form-item label="体重(kg)">
                    <el-input-number v-model="form.weight" :min="0" :precision="1" />
                </el-form-item>
                <el-form-item label="血压">
                    <el-input v-model="form.bloodPressure" placeholder="格式：120/80" />
                </el-form-item>
                <el-form-item label="血糖">
                    <el-input-number v-model="form.bloodGlucose" :min="0" :precision="1" />
                </el-form-item>
                <el-form-item label="血氧">
                    <el-input-number v-model="form.bloodOxygen" :min="0" :max="100" />
                </el-form-item>
                <el-form-item label="心率">
                    <el-input-number v-model="form.heartRate" :min="0" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="confirmSubmit">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted , computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
    queryIndicator,
    updateIndicator,
    deleteIndicator,
    addIndicator
} from '@/api/indicator';

// 表格数据
const tableData = ref([]);

// 计算用户角色
const isAdminOrDoctor = computed(() => {
    const role = localStorage.getItem('role');
    return role === 'doctor' || role === 'admin';
});

// 加载健康指标
const loadHealthIndicators = async (params) => {
    try {
        // 医生权限验证
        if (isAdminOrDoctor.value) {
            if (!/^\d+$/.test(searchForm.value.userId)) {
                ElMessage.error('请输入有效的用户ID');
                return;
            }
        }

        const userId = isAdminOrDoctor.value
            ? searchForm.value.userId
            : localStorage.getItem('id');

        const requestParams = {
            userId: parseInt(userId),
            startDate: params?.startDate || "2000-01-01",
            endDate: params?.endDate || "3000-01-01",
            pageIndex: 0,
            pageSize: 10
        };

        const response = await queryIndicator(requestParams);

        if (response.code === '000') {
            tableData.value = response.data.records || [];
            localStorage.setItem('aimid', parseInt(userId)); // 存储用户ID到本地存储
        } else {
            ElMessage.error(`获取健康指标失败: ${response.msg}`);
        }
    } catch (error) {
        ElMessage.error(`获取健康指标时出错: ${error.message}`);
    }
};

// 格式化日期
const formatDate = (dateString) => {
    if (!dateString) return '';
    const date = new Date(dateString);
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
};

// 修改搜索表单结构
const searchForm = ref({
    userId: '', // 新增用户ID字段
    startDate: "2020-01-01",
    endDate: "2025-05-31"
});

const handleSearch = () => {

    loadHealthIndicators(searchForm.value);
};

// 对话框相关
const dialogVisible = ref(false);
const dialogTitle = ref('新增健康指标');
const form = ref({
    indicatorId: 0,
    userId: 1,
    height: 0,
    weight: 0,
    bmi: 0,
    bloodPressure: '',
    bloodGlucose: 0,
    bloodOxygen: 0,
    heartRate: 0
});

// 打开新增对话框
const handleAdd = () => {

    // 设置默认用户ID
    let defaultUserId = localStorage.getItem('id');
    if (isAdminOrDoctor.value) {
        defaultUserId = searchForm.value.userId || defaultUserId;
    }

    // 重置表单
    form.value = {
        indicatorId: 0,
        userId: localStorage.getItem('userId') || 1,
        height: 0,
        weight: 0,
        bmi: 0,
        bloodPressure: '',
        bloodGlucose: 0,
        bloodOxygen: 0,
        heartRate: 0
    };
    dialogTitle.value = '新增健康指标';
    dialogVisible.value = true;
};

// 打开编辑对话框
const handleUpdate = (row) => {
    form.value = {
        indicatorId: row.indicatorId,
        userId: row.userId,
        height: row.height,
        weight: row.weight,
        bmi: row.bmi,
        bloodPressure: row.bloodPressure,
        bloodGlucose: row.bloodGlucose,
        bloodOxygen: row.bloodOxygen,
        heartRate: row.heartRate
    };
    dialogTitle.value = '编辑健康指标';
    dialogVisible.value = true;
};

// 确认提交（新增或编辑）
const confirmSubmit = async () => {
    try {
        if (dialogTitle.value === '新增健康指标') {
            // 新增记录
            const addParams = {
                userId: localStorage.getItem('id'),
                height: form.value.height,
                weight: form.value.weight,
                bmi: form.value.bmi,
                bloodPressure: form.value.bloodPressure,
                bloodGlucose: form.value.bloodGlucose,
                bloodOxygen: form.value.bloodOxygen,
                heartRate: form.value.heartRate
            };

            const response = await addIndicator(addParams);

            if (response.code === '000') {
                ElMessage.success('新增成功');
                dialogVisible.value = false;
                loadHealthIndicators(searchForm.value); // 刷新数据
            } else {
                ElMessage.error(`新增失败: ${response.msg}`);
            }
        } else {
            // 编辑记录
            const updateParams = {
                indicatorId: form.value.indicatorId,
                userId: form.value.userId,
                height: form.value.height,
                weight: form.value.weight,
                bmi: form.value.bmi,
                bloodPressure: form.value.bloodPressure,
                bloodGlucose: form.value.bloodGlucose,
                bloodOxygen: form.value.bloodOxygen,
                heartRate: form.value.heartRate
            };

            const response = await updateIndicator(updateParams);

            if (response.code === '000') {
                ElMessage.success('更新成功');
                dialogVisible.value = false;
                loadHealthIndicators(searchForm.value); // 刷新数据
            } else {
                ElMessage.error(`更新失败: ${response.msg}`);
            }
        }
    } catch (error) {
        ElMessage.error(`操作时出错: ${error.message}`);
    }
};

// 处理删除
const handleDelete = async (row) => {
    try {
        const confirm = await ElMessageBox.confirm(
            '确定要删除这条健康指标吗？',
            '警告',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        );

        if (confirm === 'confirm') {
            const params = { indicatorId: row.indicatorId };
            const response = await deleteIndicator(params);

            if (response.code === '000') {
                ElMessage.success('删除成功');
                loadHealthIndicators(searchForm.value); // 刷新数据
            } else {
                ElMessage.error(`删除失败: ${response.msg}`);
            }
        }
    } catch (error) {
        // 用户取消删除或发生错误
        if (error !== 'cancel') {
            ElMessage.error(`删除时出错: ${error.message}`);
        }
    }
};

// 页面加载时获取数据
onMounted(() => {
    // 设置默认用户ID
    let defaultUserId = localStorage.getItem('id');
    if (isAdminOrDoctor.value) {
        defaultUserId = searchForm.value.userId || defaultUserId;
    }
    loadHealthIndicators();
});
</script>

<style scoped>
.health-indicator-container {
    padding: 20px;
    background-color: #f5f7fa;
}

.header {
    margin-bottom: 20px;
    margin-right: 200px;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.search {
    display: flex;
    gap: 10px;
}

.search .el-date-editor {
    width: auto;
}
</style>